<?php

namespace app\api\controller;

use think\Db;
use think\Image;
use OSS\OssClient;
use app\api\model\Task;

class Faceidvb extends Common
{
    protected $expired;

    public function _initialize()
    {
        parent::_initialize();

        $this->expired = '3600';
    }

    /**
     * 使用 AK，SK 生成鉴权签名（Access Token）
     * @return string 鉴权签名信息（Access Token）
     */
    private function getAccessToken(){
        $curl = curl_init();
        $postData = array(
            'grant_type' => 'client_credentials',
            'client_id' => getenv('BAIDU_AUDIO_APP_KEY'),
            'client_secret' => getenv('BAIDU_AUDIO_SECRET_KEY')
        );
        curl_setopt_array($curl, array(
            CURLOPT_URL => 'https://aip.baidubce.com/oauth/2.0/token',
            CURLOPT_CUSTOMREQUEST => 'POST',
            CURLOPT_SSL_VERIFYPEER  => false,
            CURLOPT_SSL_VERIFYHOST  => false,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_POSTFIELDS => http_build_query($postData)
        ));
        $response = curl_exec($curl);
        curl_close($curl);
        $rtn = json_decode($response);
        return $rtn->access_token;
    }


    private function imagesUpload($file)
    {
        $switch = getenv('APP_OSS');

        $image = Image::open($file);

        $path = ROOT_PATH . 'disk' . DS . 'uploads' . DS . 'images';
        $info = $file->move($path);

        if ($info) {
            $img = 'disk/uploads/images/' . $info->getSaveName();
            $img = $fileName = str_replace('\\', '/', $img);

            $image->thumb(1000, 1000)->save($img);

            if ($switch) {
                $localFile = str_replace('/index.php', '', $_SERVER['SCRIPT_FILENAME']) . '/'.$img;

                $accessKeyId = getenv('OSS_KEYID');
                $accessKeySecret = getenv('OSS_KEYSECRET');
                $endpoint = getenv('OSS_ENDPOINT');
                $bucket = getenv('OSS_BUCKET');

                $ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint);
                $ossClient->uploadFile($bucket, $fileName, $localFile);

                //unlink($localFile);
            }

            return $img;
        } else {
            return $file->getError();
        }
    }

    public function get_biz_token() {
        if ($this->member['reg'] != 1) return $this->miss('请重启APP再次尝试');
        $user_id = $this->member['id'];
        $attestation = Db::name('user')->where(['id' => $user_id])->value('is_identity_authentication');
        if ($attestation && $attestation == 2) return $this->miss('已认证过');

        $image1 = request()->file("image_ref1");

        $image1up = $this->imagesUpload($image1);
        $file=iconv("UTF-8","gb2312", $image1up);
        $image_ref1=new \CURLFile($file);

        $params = [
            'image'=>explode(';base64,',base64EncodeImage($file))[1],
            'image_type'=>'BASE64',
            'face_field'=>'age,expression,face_shape,gender,glasses,landmark,landmark150,quality,eye_status,emotion,face_type,mask,spoofing',
            'liveness_control'=>'HIGH'
        ];
        $url = "https://aip.baidubce.com/rest/2.0/face/v3/detect?access_token={$this->getAccessToken()}";
        $result = http_post($url, $params);
        // var_dump($result);exit;
        if (!$result || $result['error_code'] != 0) {
            return $this->miss('识别人脸失败');
        }
        $biztoken = $result['result']['face_list'][0]['face_token'];

        Db::name('auth')->where(['user_id' => $user_id])->delete();
        Db::name('auth')->insert([
            'user_id' => $user_id,
            'idcard_name' => '',
            'idcard_number' =>'',
            'image_ref1' => $image_ref1,
            'image_ref2' => '',
            'image1' => $image1up ? '/'.$image1up : '',
            'image2' => '',
            'token' => $biztoken,
            'create_time' => time()
        ]);

        return $this->pass($biztoken);
        // return $this->pass($result['result']['face_list'][0]['face_token']);
    }

    public function auth()
    {
        $user_id = $this->member['id'];
        $meglive_data = input('meglive_data','');
        $attestation = Db::name('user')->where(['id' => $user_id])->value('attestation');
        if ($attestation) return $this->miss('已认证过');

        // 去表里查询是否有上传过照片，如果有，先看biztoken是否已过期，如果过期，将以前上传存到表里的照片重新传到接口biz_token()获取token
        $res = Db::name('auth')->where(['user_id' => $user_id])->find();
        if (!$res) {
            return $this->miss('请重新验证');
        }
        if (($res['create_time'] + $this->expired) < time()) {
            return $this->miss('请重新开始');
        }
        $biztoken = $res['token'];


        $url = "https://aip.baidubce.com/rest/2.0/face/v3/match?access_token={$this->getAccessToken()}";
        $params = [
            [
                'image'=>$res['token'],
                'image_type'=>'FACE_TOKEN',
                'face_type'=>'LIVE',
                'quality_control'=>'LOW',
                'liveness_control'=>'NORMAL',
            ],
            [
                'image'=>$meglive_data,
                'image_type'=>'BASE64',
                'face_type'=>'LIVE',
                'quality_control'=>'LOW',
                'liveness_control'=>'NORMAL',
            ],
        ];
        $result = http_post($url, $params);

        if (!$result || $result['error_code'] != 0) {
            return $this->miss('人脸匹配异常');
        }
        // return $this->pass($result);
        if ($result['result']['score'] < 80) {
            return $this->miss('人脸匹配失败');
        }

        $res = Db::name('auth')->where(['user_id' => $user_id])->find();
        if ($res['image1']) {
            Db::name('user_img')->insert([
                'user_id' => $user_id,
                'pic' => json_encode([$res['image1']]),
                'picthumb' => json_encode([$res['image1']]),
                'burn' => 0,
                'packet' => 0,
                'is_auth' => 1,
                'is_face' => 1
            ]);
        }

        // 任务
        Task::finish('real_auth', $user_id);

        Db::name('user')->where(['id' => $user_id])->update([
            // 'head_100' => $res['image1'],
            // 'head_300' => $res['image1'],
            // 'head_portrait' => $res['image1'],
            'attestation' => 1,
            'is_identity_authentication' => 2
        ]);
        return $this->pass('success');
    }
}

